<script setup>
  import { ref,toRefs,shallowRef,nextTick,watch } from 'vue';
  import { protocolList } from '../assets/protocolList.js';
  import { modifyDeviceList } from '@/api/DevConnection';
  import { message } from '@/utils/message';
  import { useDrawerStore } from '@/store/drawerDataStores.js';
  import componentList from './index.js';

  const drawerStore = useDrawerStore();

  const childFuncRef = ref(),
    ruleFormRef = ref(),
    publicForm = ref({
      inputGatewayId: undefined,
      selectedInterface: undefined,
      selectedProtocol: undefined
    }),
    gatewayStatus = ref(''),
    protocolStatus = ref(''),
    compileRate = ref(0),
    issueRate = ref(0),
    compileDisabled = ref(true),
    issueDisabled = ref(true);


  const props = defineProps({
    protocolConfigDrawer: {
      type: Boolean,
      default: false
    },
    devVarTableSelectedItem: {
      type: Object,
      default() {
        return {}
      }
    },
    // tableSelectedId: {
    //   type: Number,
    //   default: ''
    // }
  });
  const { protocolConfigDrawer, devVarTableSelectedItem } = toRefs(props);
  const emit = defineEmits(['childProtocolDrawer', 'childGetApiTableDataList']);

<<<<<<< HEAD
  watch(() => [publicForm.value.inputGatewayId,publicForm.value.selectedInterface,publicForm.value.selectedProtocol], (newValue, oldValue) => {
    compileRate.value = 0;
    protocolStatus.value = '';
    issueRate.value = 0;
    gatewayStatus.value = '';
    issueDisabled.value = true;
    compileDisabled.value = true;
=======
  watch(() => publicForm.value.selectedProtocol, (newValue, oldValue) => {
    // console.log(`value 从 ${oldValue} 变为 ${newValue}`);
>>>>>>> 3b24feac27ff1f3481308d21c3f5277aa3dbd283
  });

  // 协议更改事件
  const protocolLabel = ref('');
  const component = shallowRef(null);
  const protocolChange = (value) => {
    let strName = '';
    if (value) {
      protocolList.forEach(item => {
        if (item.value === value) {
          protocolLabel.value = item.label;
        }
      });
      strName = protocolLabel.value.replace(/\s+/g, "");
    }
    componentList.value.filter((item) => {
      if (item.key === strName) {
        component.value = item.component;
      }
    });
    if (component.value) {
      nextTick(() => {
        childFuncRef.value.clearVar();
      })
    }
  }

  // 编译按钮
  const compileClick = () => {
    let compile_timer = setInterval(()=>{
      protocolStatus.value = "编译中";
      if(compileRate.value < 100){
        compileRate.value++;
      } else {
        clearInterval(compile_timer);
        protocolStatus.value = "编译完成";
        issueDisabled.value = false;
      }
    },30)
  };
  // form子组件传值
  const childFormObjChange = (formObj) => {
    ruleFormRef.value.validate((valid) => {
      if (valid) {
        childSubmitForm(formObj);
      } else {
        return false;
      }
    });
  }
  // 下发按钮
  const issueClick = () => {
    let issue_timer = setInterval(()=>{
      protocolStatus.value = "下发中";
      if(issueRate.value < 100){
        issueRate.value++;
      } else {
        clearInterval(issue_timer);
        protocolStatus.value = "下发完成";
      }
    },30)

    setTimeout(() => {
      protocolStatus.value = "适配完成";
      gatewayStatus.value = "运行";
    }, 5000);
  };
  // 清空已经填写的变量
  const deleteVar = () => {
<<<<<<< HEAD
=======
    publicForm.value.inputGatewayId = undefined;
    publicForm.value.selectedInterface = undefined;
    publicForm.value.selectedProtocol = undefined;
>>>>>>> 3b24feac27ff1f3481308d21c3f5277aa3dbd283
    protocolLabel.value = '';
    ruleFormRef.value.resetFields();
    nextTick(() => {
      childFuncRef.value.clearVar();
    })
  }
  // 抽屉取消按钮
  const cancelClick = () => {
    emit('childProtocolDrawer', false);
    if (publicForm.value.selectedProtocol) {
      deleteVar();
    }
  };

  // 抽屉确定按钮
  const confirmClick = () => {
    emit('childProtocolDrawer', false);
    drawerStore.inputGatewayId = publicForm.value.inputGatewayId;
    drawerStore.selectedInterface = publicForm.value.selectedInterface;
    drawerStore.selectedProtocol = publicForm.value.selectedProtocol;
    drawerStore.tableSelectedId = devVarTableSelectedItem.value.id;
    drawerStore.formTitle = protocolLabel.value;
    nextTick(() => {
      childFuncRef.value.saveStore();
    })
  };

  // 抽屉关闭回调
  const handleClose = () => {
    emit('childProtocolDrawer', false);
    if (publicForm.value.selectedProtocol) {
      deleteVar();
    }
  };

  // 抽屉打开回调
  const handleOpen = () => {
    if (drawerStore.tableSelectedId === devVarTableSelectedItem.value.id) {
      publicForm.value.inputGatewayId = drawerStore.inputGatewayId;
      publicForm.value.selectedInterface = drawerStore.selectedInterface;
      publicForm.value.selectedProtocol = drawerStore.selectedProtocol;
      protocolLabel.value = drawerStore.formTitle;
      nextTick(() => {
        childFuncRef.value.copyStore();
      })
    } else if (devVarTableSelectedItem.value.state === 1) {
      publicForm.value.inputGatewayId = devVarTableSelectedItem.value.gatewayId;
      publicForm.value.selectedInterface = devVarTableSelectedItem.value.connector;
      publicForm.value.selectedProtocol = devVarTableSelectedItem.value.protocol;
      protocolList.forEach(item => {
        if (item.value === devVarTableSelectedItem.value.protocol) {
          protocolLabel.value = item.label;
        }
      })
      let strName = protocolLabel.value.replace(/\s+/g, "");
      componentList.value.filter((item) => {
        if (item.key === strName) {
          component.value = item.component;
        }
      });
      nextTick(() => {
        childFuncRef.value.copyStore();
      })
    } else if (!devVarTableSelectedItem.value.selectedProtocol) {
      component.value = null;
    }
  };
  // 子组件提交表单
  const childSubmitForm = (childObject) => {
    let parentObj = {
      id: devVarTableSelectedItem.value.id,
      deviceType: devVarTableSelectedItem.value.deviceType, // 设备类型
      deviceName: devVarTableSelectedItem.value.deviceName, // 设备名称
      deviceDescription: devVarTableSelectedItem.value.deviceDescription, // 设备描述
      state: 1, // 0:未适配，1：已适配
      gatewayId: publicForm.value.inputGatewayId, // 网关Id
      createUser: '', // 创建人
      updateUser: '', // 修改人
      isDeleted: 0, // 0：未删除，1：已删除
      connector: publicForm.value.selectedInterface, // 接入口
      protocol: publicForm.value.selectedProtocol, // 协议
      passiveAddress: '', // 从站地址
      passiveIp: '', // 从站ip
      passivePort: '', // 端口号
      protocolType: '', // 协议类型
      protocolAddress: '', // 协议地址
      protocolNumber: '', // 协议数量
      targetAddress: '', // 目标地址
      targetPort: '', // 目标端口
      deviceAccount: '', // 设备账户
      devicePassword: '', // 设备密码
      clientId: '', // ClientID
      subscribeTopic: '', // 订阅主题
      releaseTopic: '', // 发布主题
      qos: '', // QOS
      clearSession: '', // 清理会话状态
      url: '', // URL
      securityPolicy: '', // 安全策略
      nodePath: '', // 节点路径
      certificates: '', // 证书和密钥
      readingMethod: '', // 数据读取方法
      timeoutSetting: '', // 超时设置
      baudRate: '', // 波特率
      dataBit: '', // 数据位
      stopBit: '', // 停止位
      verify: '', // 校验
      frameFormat: '', // 帧格式
      frameType: '', // 帧类型
      frameId: '', // 帧ID
      wifiAccount: '', // WIFI账号
      wifiPassword: '', // WIFI密码
      isSelected: 1, // 是否选中
    }
    const submitObject = { ...parentObj, ...childObject };
    modifyDeviceList(submitObject).then(res => {
      if (res.status === 200) {
        compileRate.value = 0;
        issueRate.value = 0;
        protocolStatus.value = '配置中';
        gatewayStatus.value = '预运行';
        compileDisabled.value = true;
        setTimeout(() => {
          protocolStatus.value = '配置完成';
          gatewayStatus.value = '预运行';
          compileDisabled.value = false;
        }, 2000);
        emit('childGetApiTableDataList');
      } else {
        message(res.message, { type: 'error' });
        console.log()
      }
    })
  };
</script>

<template>
  <el-drawer
    :model-value="protocolConfigDrawer"
    direction="rtl"
    @open="handleOpen"
    @close="handleClose"
  >
    <template #header>
      <h4>协议配置</h4>
    </template>
    <template #default>
      <div class="drawer-main">
        <div class="drawer-one">
          <el-form
            ref="ruleFormRef"
            :inline="true"
            :model="publicForm"
            label-position="top"
          >
            <el-form-item
              label="网关ID"
              style="width: 140px;"
              prop="inputGatewayId"
              :rules="{ required: true, message: '请输入网关ID', trigger: 'blur' }"
            >
              <el-input v-model="publicForm.inputGatewayId" clearable placeholder="请输入网关ID"></el-input>
            </el-form-item>
            <el-form-item
              label="接口"
              style="width: 140px;"
              prop="selectedInterface"
              :rules="{ required: true, message: '请选择接口', trigger: 'change' }"
            >
              <el-select
                v-model="publicForm.selectedInterface"
                placeholder="请选择接口"
              >
                <el-option label="无接口" value="无接口" />
                <el-option label="RJ45_1" value="RJ45_1" />
                <el-option label="RJ45_2" value="RJ45_2" />
              </el-select>
            </el-form-item>
            <el-form-item
              label="协议"
              style="width: 140px;"
              prop="selectedProtocol"
              :rules="{ required: true, message: '请选择接口', trigger: 'change' }"
            >
              <el-select
                v-model="publicForm.selectedProtocol"
                placeholder="请选择协议"
                @change="protocolChange"
              >
                <el-option
                  v-for="item in protocolList"
                  :key="item"
                  :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="drawer-two">
          <el-divider content-position="left">参数配置</el-divider>
          <div class="form-title">{{ protocolLabel }}</div>
          <keep-alive>
            <component
              ref="childFuncRef"
              :is="component"
              :public-form="publicForm"
              :devVarTableSelected-item="devVarTableSelectedItem"
              @childFormObj="childFormObjChange"
            ></component>
          </keep-alive>
        </div>
        <div class="drawer-three">
          <el-divider content-position="left">协议更新与部署</el-divider>
          <div class="three-main">
            <div class="three-item">
              <div class="progress-box">
                <el-progress :percentage="compileRate" :text-inside="true" :stroke-width="30"/>
              </div>
              <el-button link type="primary" @click="compileClick" :disabled="compileDisabled">编译</el-button>
            </div>
            <div class="three-item">
              <div class="progress-box">
                <el-progress :percentage="issueRate" :text-inside="true" :stroke-width="30"/>
              </div>
              <el-button link type="primary" @click="issueClick" :disabled="issueDisabled">下发</el-button>
            </div>
          </div>
        </div>
        <div class="drawer-four">
          <el-divider content-position="left">适配状态</el-divider>
          <div class="four-status-main">
            <div class="four-item">
              <div class="four-title">协议适配状态</div>
              <el-tag class="custom-tag">{{ protocolStatus }}</el-tag>
            </div>
            <div class="four-item">
              <div class="four-title">边缘网关状态</div>
              <el-tag class="custom-tag">{{ gatewayStatus }}</el-tag>
            </div>
          </div>
        </div>
      </div>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style>
.el-drawer__body::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
	border-radius: 8px;
	background-color: #F5F5F5;
}

.el-drawer__body::-webkit-scrollbar {
  width: 8px;
	background-color: #F5F5F5;
}

.el-drawer__body::-webkit-scrollbar-thumb {
  border-radius: 8px;
	-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
	background-color: #8b8b8b;
}
</style>
<style lang="scss" scoped>
  .drawer-main {
    height: 100%;
    display: flex;
    flex-direction: column;

    .drawer-one {
      flex: 0 0 auto;
    }

    .drawer-two {
      flex: auto;
      .form-title {
        font-size: 18px;
        font-weight: 700;
        padding-bottom: 18px;
      }
    }

    .drawer-three {
      flex: 0 0 auto;

      .three-main {
        .three-item {
          display: flex;
          align-items: center;

          .progress-box {
            padding-right: 20px;
            flex: 1;
          }
        }

        .three-item + .three-item {
          margin-top: 15px;
        }
      }
    }

    .drawer-four {
      flex: 0 0 auto;

      .four-status-main {
        display: flex;
        justify-content: space-around;

        .four-item {
          .four-title {
            text-align: center;
            font-size: 16px;
            padding-bottom: 5px;
          }

          .custom-tag {
            width: 200px;
            background-color: #f5f7fa
          }
        }
      }
    }
  }
</style>
